<template>
  <!-- 回到顶部 -->
  <div class="back-top" :class="{ hidden: !show }" @click="goTop()">
    <img src="@/assets/img/top.png" />
  </div>
</template>

<script>
export default {
  name: 'BackTop',
  props: {
    selector: String,
  },
  data() {
    return {
      el: {},
      show: false,
    }
  },
  mounted() {
    // 监听滚动事件
    this.el = document.querySelector(this.selector)
    this.el.addEventListener('scroll', this.handleScroll)
  },
  destroyed() {
    // 移除滚动事件
    this.el.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    goTop() {
      this.el.scrollTo({ top: 0, behavior: 'smooth' })
    },
    handleScroll() {
      // 滚动距离顶部的距离
      if (this.el.scrollTop > 200) {
        this.show = true
      } else {
        this.show = false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.back-top {
  position: fixed;
  right: 15px;
  bottom: 60px;
  z-index: 999;
  &.hidden {
    display: none;
  }
}
.back-top img {
  width: 43px;
  height: 43px;
}
</style>
